import sys
import traceback
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import math
import random


def exception_hook(exctype, value, tb):
    traceback.print_exception(exctype, value, tb)


sys.excepthook = exception_hook


class RulesDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("游戏规则")
        self.setModal(True)
        self.resize(600, 400)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 创建文本浏览器控件，支持富文本
        self.text_browser = QTextBrowser()
        self.text_browser.setOpenExternalLinks(True)  # 允许打开外部链接

        # 读取规则文件
        self.load_rules()

        layout.addWidget(self.text_browser)

        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        layout.addWidget(close_btn)

        self.setLayout(layout)

    def load_rules(self):
        """读取规则文件"""
        try:
            # 尝试读取规则文件
            with open('./rules.txt', 'r', encoding='utf-8') as f:
                rules_content = f.read()
                self.text_browser.setHtml(rules_content)
        except FileNotFoundError:
            # 如果文件不存在，显示默认规则
            default_rules = """
            <h1>小兵小兵游戏规则</h1>
            <p>规则文件 rules.txt 未找到。</p>
            <p>请确保规则文件位于程序同一目录下。</p>
            """
            self.text_browser.setHtml(default_rules)
        except Exception as e:
            # 其他错误
            error_msg = f"<h1>错误</h1><p>读取规则文件时发生错误：{str(e)}</p>"
            self.text_browser.setHtml(error_msg)


class PlayerArea(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_page = parent
        self.hovered_player = None
        self.setMouseTracking(True)

    def paintEvent(self, event):
        """绘制事件"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        if not self.parent_page or not self.parent_page.game:
            return

        player_positions = self.parent_page.calculate_player_positions()

        # 首先绘制所有玩家头像和状态
        for player, pos in player_positions.items():
            self.draw_player(painter, player, pos)

            # 绘制操作图标（只有在游戏已经开始且玩家有操作且玩家存活时才显示）
            if (self.parent_page.game_started and
                    player.operation.type != OperationType.NONE and
                    player.alive):  # 只显示存活玩家的操作
                if player.operation.type == OperationType.LOAD:
                    self.draw_load(painter, pos)
                elif player.operation.type == OperationType.DEFENCE:
                    self.draw_defence(painter, pos)

            # 绘制死亡标记
            if not player.alive:
                self.draw_death(painter, pos)

        # 然后绘制攻击箭头（确保箭头在最上层）
        for player, pos in player_positions.items():
            if (self.parent_page.game_started and
                    player.operation.type == OperationType.ATTACK and
                    player.operation.attack_target and
                    player.operation.attack_target in player_positions and
                    player.alive):  # 只显示存活玩家的攻击箭头
                target_pos = player_positions[player.operation.attack_target]
                self.draw_attack_arrow(painter, pos, target_pos, player.operation.attack_ammo)

        # 最后绘制悬浮红框（确保在最上层）
        if self.hovered_player and self.hovered_player in player_positions:
            pos = player_positions[self.hovered_player]
            self.draw_hover_frame(painter, pos)

    def draw_player(self, painter, player, position):
        """绘制玩家头像和名字"""
        x, y = position

        # 绘制头像背景
        painter.setBrush(QColor(240, 240, 240))
        painter.setPen(QPen(Qt.GlobalColor.black, 1))
        painter.drawEllipse(x - 32, y - 32, 64, 64)

        # 尝试加载图片
        try:
            if player.is_ai:
                pixmap = QPixmap("./ai.png")
            else:
                pixmap = QPixmap("./player.png")

            if not pixmap.isNull():
                # 缩放图片到适当大小
                pixmap = pixmap.scaled(60, 60, Qt.AspectRatioMode.KeepAspectRatio,
                                       Qt.TransformationMode.SmoothTransformation)
                painter.drawPixmap(x - 30, y - 30, pixmap)
        except:
            # 如果图片加载失败，绘制圆形替代
            painter.setBrush(QColor(200, 200, 200))
            painter.drawEllipse(x - 30, y - 30, 60, 60)

        # 在头像右下角绘制弹药数（大字号）
        painter.setPen(Qt.GlobalColor.black)
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        painter.setFont(font)

        # 绘制弹药背景
        painter.setBrush(QColor(255, 255, 255, 200))  # 半透明白色背景
        painter.drawEllipse(x + 15, y + 15, 30, 30)

        # 绘制弹药数
        painter.drawText(x + 15, y + 15, 30, 30, Qt.AlignmentFlag.AlignCenter, str(player.ammo))

        # 绘制玩家名字 - 使用默认颜色和更大字号
        font.setPointSize(10)  # 加大字号
        font.setBold(True)  # 保持粗体
        painter.setFont(font)
        # 使用默认颜色，让系统自动适应主题
        painter.setPen(QPen(QApplication.palette().text().color(), 1))
        painter.drawText(x - 40, y + 45, 80, 20, Qt.AlignmentFlag.AlignCenter, player.name)

    def draw_load(self, painter, position):
        """绘制装弹操作"""
        x, y = position
        painter.setPen(QPen(QColor(0, 255, 0), 3))  # 绿色
        # 绘制加号，超出玩家头像约40px
        painter.drawLine(x - 40, y, x + 40, y)
        painter.drawLine(x, y - 40, x, y + 40)

    def draw_defence(self, painter, position):
        """绘制防御操作"""
        x, y = position
        # 设置空心圆圈
        painter.setBrush(Qt.BrushStyle.NoBrush)
        painter.setPen(QPen(QColor(0, 0, 255), 3))  # 蓝色
        # 空心圆圈，更大一点
        painter.drawEllipse(x - 45, y - 45, 90, 90)

    def draw_attack_arrow(self, painter, start_pos, end_pos, ammo_type):
        """绘制攻击箭头"""
        x1, y1 = start_pos
        x2, y2 = end_pos

        # 根据弹药类型选择颜色
        if ammo_type == 1:
            color = QColor(255, 200, 0)  # 黄色 - 单枪
            width = 3
        elif ammo_type == 2:
            color = QColor(255, 0, 0)  # 红色 - 双枪
            width = 4
        else:  # 核弹
            color = QColor(128, 0, 128)  # 紫色 - 核弹
            width = 5

        painter.setPen(QPen(color, width))

        # 绘制箭头线
        painter.drawLine(x1, y1, x2, y2)

        # 计算箭头
        angle = math.atan2(y2 - y1, x2 - x1)
        arrow_size = 20

        # 箭头点1
        x3 = x2 - arrow_size * math.cos(angle - math.pi / 6)
        y3 = y2 - arrow_size * math.sin(angle - math.pi / 6)
        # 箭头点2
        x4 = x2 - arrow_size * math.cos(angle + math.pi / 6)
        y4 = y2 - arrow_size * math.sin(angle + math.pi / 6)

        painter.drawLine(x2, y2, int(x3), int(y3))
        painter.drawLine(x2, y2, int(x4), int(y4))

    def draw_death(self, painter, position):
        """绘制死亡标记"""
        x, y = position
        painter.setPen(QPen(QColor(255, 0, 0), 3))  # 红色
        painter.drawLine(x - 35, y - 35, x + 35, y + 35)
        painter.drawLine(x - 35, y + 35, x + 35, y - 35)

    def draw_hover_frame(self, painter, position):
        """绘制悬浮红框"""
        x, y = position
        # 设置空心红框
        painter.setBrush(Qt.BrushStyle.NoBrush)
        painter.setPen(QPen(QColor(255, 0, 0), 2))  # 红色边框
        painter.drawRect(x - 40, y - 40, 80, 80)

    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if self.parent_page and hasattr(self.parent_page, 'current_operation_type'):
            player = self.get_player_at_position(event.pos())
            # 只对存活的非玩家角色显示红框
            if player and player.name != "玩家" and player.alive:
                self.hovered_player = player
            else:
                self.hovered_player = None
            self.update()

    def mousePressEvent(self, event):
        """鼠标点击事件"""
        if event.button() == Qt.MouseButton.LeftButton and self.parent_page:
            player = self.get_player_at_position(event.pos())
            # 只对存活的非玩家角色响应点击
            if (player and player.name != "玩家" and player.alive and
                    hasattr(self.parent_page, 'current_operation_type') and
                    hasattr(self.parent_page, 'current_attack_ammo')):  # 确保属性存在
                self.parent_page.confirm_attack_operation(
                    self.parent_page.current_operation_type,
                    self.parent_page.current_attack_ammo,
                    player
                )

    def get_player_at_position(self, pos):
        """根据位置获取玩家"""
        if not self.parent_page:
            return None

        player_positions = self.parent_page.calculate_player_positions()
        for player, position in player_positions.items():
            rect = QRect(position[0] - 35, position[1] - 35, 70, 70)
            if rect.contains(pos):
                return player
        return None


class StartPage(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 标题
        title = QLabel("小兵小兵")
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_font = QFont()
        title_font.setPointSize(24)
        title.setFont(title_font)
        layout.addWidget(title)

        layout.addStretch()

        # 游戏模式选择按钮
        button_layout = QVBoxLayout()

        offline_btn = QPushButton("离线")
        online_btn = QPushButton("在线")
        rules_btn = QPushButton("规则")

        # 设置按钮样式和大小
        for btn in [offline_btn, online_btn, rules_btn]:
            btn.setFixedHeight(40)
            btn.setStyleSheet("QPushButton { font-size: 14px; }")

        offline_btn.clicked.connect(self.main_window.start_offline_game)
        online_btn.setEnabled(False)
        rules_btn.clicked.connect(self.show_rules_dialog)

        button_layout.addWidget(offline_btn)
        button_layout.addWidget(online_btn)
        button_layout.addWidget(rules_btn)
        layout.addLayout(button_layout)

        layout.addStretch()

        # 版本选择
        version_layout = QHBoxLayout()
        version_label = QLabel("版本:")
        self.version_combo = QComboBox()
        self.version_combo.addItem("2")
        version_layout.addWidget(version_label)
        version_layout.addWidget(self.version_combo)
        version_layout.addStretch()
        layout.addLayout(version_layout)

        # 官方文档链接
        doc_label = QLabel('<a href="https://gitee.com/vincentqiqi/XBXB">官方文档</a>')
        doc_label.setOpenExternalLinks(True)
        doc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(doc_label)

        self.setLayout(layout)

    def show_rules_dialog(self):
        """显示规则对话框"""
        dialog = RulesDialog(self)
        dialog.exec()


class AISelectionDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("选择AI玩家数量")
        self.setModal(True)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        layout.addWidget(QLabel("选择AI玩家数量:"))

        self.ai_spinbox = QSpinBox()
        self.ai_spinbox.setRange(1, 100)  # 提高AI玩家上限到100
        self.ai_spinbox.setValue(2)
        layout.addWidget(self.ai_spinbox)

        button_layout = QHBoxLayout()
        ok_btn = QPushButton("确定")
        cancel_btn = QPushButton("取消")

        ok_btn.clicked.connect(self.accept)
        cancel_btn.clicked.connect(self.reject)

        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        layout.addLayout(button_layout)

        self.setLayout(layout)


class OfflinePage(QWidget):
    def __init__(self, main_window, ai_count=2):
        super().__init__()
        self.main_window = main_window
        self.ai_count = ai_count
        self.game = Game()
        self.selected_target = None
        self.current_operation_type = None
        self.game_started = False  # 标记游戏是否已经开始
        self.game_ended = False  # 标记游戏是否结束
        self.init_ui()
        self.init_game()

    def setup_shortcuts(self):
        """设置全局快捷键"""
        # 装弹 - Q
        QShortcut(QKeySequence("Q"), self).activated.connect(
            lambda: self.confirm_attack_operation(OperationType.LOAD) if not self.game_ended else None)

        # 防御 - W
        QShortcut(QKeySequence("W"), self).activated.connect(
            lambda: self.confirm_attack_operation(OperationType.DEFENCE) if not self.game_ended else None)

        # 开枪 - E
        QShortcut(QKeySequence("E"), self).activated.connect(
            lambda: self.prepare_attack(OperationType.ATTACK, 1) if not self.game_ended else None)

        # 双枪 - R
        QShortcut(QKeySequence("R"), self).activated.connect(
            lambda: self.prepare_attack(OperationType.ATTACK, 2) if not self.game_ended else None)

        # 核弹 - T
        QShortcut(QKeySequence("T"), self).activated.connect(
            lambda: self.prepare_attack(OperationType.ATTACK, 3) if not self.game_ended else None)

    def init_ui(self):
        main_layout = QHBoxLayout()

        # 左边玩家区域
        self.left_widget = PlayerArea(self)
        self.left_widget.setMinimumSize(400, 300)
        main_layout.addWidget(self.left_widget, 2)

        # 右边操作区域
        right_layout = QVBoxLayout()

        operations_group = QGroupBox("操作")
        operations_layout = QVBoxLayout()

        # 创建操作按钮
        self.load_btn = QPushButton("装弹 (Q)")
        self.defence_btn = QPushButton("防御 (W)")
        self.single_attack_btn = QPushButton("开枪 (E)")
        self.double_attack_btn = QPushButton("双枪 (R)")
        self.nuclear_attack_btn = QPushButton("核弹 (T)")

        # 设置按钮的尺寸策略 - 水平固定，垂直扩展
        vertical_expanding = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)
        for btn in [self.load_btn, self.defence_btn, self.single_attack_btn,
                    self.double_attack_btn, self.nuclear_attack_btn]:
            btn.setSizePolicy(vertical_expanding)
            # 移除最小高度设置

        operations_layout.addWidget(self.load_btn)
        operations_layout.addWidget(self.defence_btn)
        operations_layout.addWidget(self.single_attack_btn)
        operations_layout.addWidget(self.double_attack_btn)
        operations_layout.addWidget(self.nuclear_attack_btn)

        operations_group.setLayout(operations_layout)

        # 设置操作GroupBox的尺寸策略 - 垂直扩展
        operations_group.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding))
        right_layout.addWidget(operations_group)

        right_layout.addStretch()

        # 状态栏
        info_group = QGroupBox("状态栏")
        info_layout = QVBoxLayout()

        self.turn_label = QLabel("回合: 0")
        self.ammo_label = QLabel("你的弹药: 0")
        self.status_label = QLabel("状态: 存活")

        info_layout.addWidget(self.turn_label)
        info_layout.addWidget(self.ammo_label)
        info_layout.addWidget(self.status_label)

        info_group.setLayout(info_layout)
        right_layout.addWidget(info_group)

        # 结算按钮
        self.result_btn = QPushButton("结算")
        right_layout.addWidget(self.result_btn)

        right_widget = QWidget()
        right_widget.setLayout(right_layout)
        right_widget.setMaximumWidth(200)
        main_layout.addWidget(right_widget, 1)

        self.setLayout(main_layout)

        # 连接信号
        self.load_btn.clicked.connect(lambda: self.confirm_attack_operation(OperationType.LOAD))
        self.defence_btn.clicked.connect(lambda: self.confirm_attack_operation(OperationType.DEFENCE))
        self.single_attack_btn.clicked.connect(lambda: self.prepare_attack(OperationType.ATTACK, 1))
        self.double_attack_btn.clicked.connect(lambda: self.prepare_attack(OperationType.ATTACK, 2))
        self.nuclear_attack_btn.clicked.connect(lambda: self.prepare_attack(OperationType.ATTACK, 3))
        self.result_btn.clicked.connect(self.on_result_clicked)

        # 添加快捷键
        self.setup_shortcuts()

    def on_result_clicked(self):
        """结算按钮点击事件"""
        if self.game_ended:
            self.main_window.show_result_page(self.game.winner)
        else:
            self.main_window.show_start_page()

    def init_game(self):
        # 添加人类玩家
        self.game.add_player("玩家")

        # 添加AI玩家
        for i in range(self.ai_count):
            self.game.add_player(f"AI{i + 1}")
            ai_player = self.game.find_player_with_name(f"AI{i + 1}")
            ai_player.is_ai = True

        # 初始回合，所有玩家没有操作
        for player in self.game.active_players:
            player.operation = Operation(OperationType.NONE)

        self.update()

    def calculate(self, operation_type, attack_ammo=None, target=None):
        """接收操作并计算游戏状态"""
        try:
            # 标记游戏已经开始
            self.game_started = True

            # 设置人类玩家操作
            human_player = self.game.find_player_with_name("玩家")
            if operation_type == OperationType.ATTACK:
                human_player.operation = Operation(operation_type, attack_ammo, target)
            else:
                human_player.operation = Operation(operation_type)

            # 设置AI玩家操作（只对存活的AI玩家）
            for player in list(self.game.active_players):  # 使用列表副本避免修改集合时的迭代问题
                if player.is_ai and player.alive:
                    # 简单的AI决策
                    if player.ammo == 0:
                        player.operation = Operation(OperationType.LOAD)
                    else:
                        # 随机选择操作
                        if random.random() < 0.3:
                            player.operation = Operation(OperationType.LOAD)
                        elif random.random() < 0.5:
                            player.operation = Operation(OperationType.DEFENCE)
                        else:
                            # 攻击随机目标
                            possible_targets = [p for p in self.game.active_players if p != player and p.alive]
                            if possible_targets:
                                target = random.choice(possible_targets)
                                ammo = random.randint(1, min(3, player.ammo))
                                player.operation = Operation(OperationType.ATTACK, ammo, target)
                            else:
                                player.operation = Operation(OperationType.LOAD)

            # 执行游戏步骤
            try:
                self.game.step()
            except KeyError as e:
                # 处理remove_dead_players中的KeyError
                print(f"移除死亡玩家时发生KeyError: {e}")
                # 手动移除死亡玩家
                self.game.active_players = {p for p in self.game.active_players if p.alive}

            # 检查游戏是否结束
            self.check_game_end()

            self.update()

        except Exception as e:
            print(f"计算时发生错误: {str(e)}")
            traceback.print_exc()

    def check_game_end(self):
        """检查游戏是否结束"""
        human_player = self.game.find_player_with_name("玩家")

        # 先检查平局：所有玩家都死亡
        all_players_dead = all(not p.alive for p in self.game.players)
        if all_players_dead:
            self.game_ended = True
            self.game.winner = False  # 平局
            self.disable_all_operations()
            return

        # 检查人类玩家是否死亡
        if not human_player.alive:
            self.game_ended = True
            self.disable_all_operations()
            return

        # 检查是否只剩一个玩家存活
        alive_players = [p for p in self.game.active_players if p.alive]
        if len(alive_players) == 1:
            self.game_ended = True
            self.game.winner = alive_players[0]
            self.disable_all_operations()

    def update(self):
        """刷新页面"""
        self.update_left()
        self.update_right()

    def update_left(self):
        """刷新左边玩家区域"""
        self.left_widget.update()

    def update_right(self):
        """刷新右边操作区域"""
        human_player = self.game.find_player_with_name("玩家")

        # 更新状态栏信息
        self.turn_label.setText(f"回合: {self.game.turn}")
        self.ammo_label.setText(f"你的弹药: {human_player.ammo}")

        # 更新玩家状态
        status = "存活" if human_player.alive else "死亡"
        self.status_label.setText(f"状态: {status}")

        # 根据游戏状态更新结算按钮文本
        if self.game_ended:
            self.result_btn.setText("查看结果")
        else:
            self.result_btn.setText("返回")

        # 根据弹药数量启用/禁用按钮
        self.single_attack_btn.setEnabled(human_player.ammo >= 1 and human_player.alive and not self.game_ended)
        self.double_attack_btn.setEnabled(human_player.ammo >= 2 and human_player.alive and not self.game_ended)
        self.nuclear_attack_btn.setEnabled(human_player.ammo >= 3 and human_player.alive and not self.game_ended)

        # 如果游戏结束，禁用所有操作
        if self.game_ended:
            self.disable_all_operations()

    def prepare_attack(self, operation_type, ammo):
        """准备攻击操作，等待选择目标"""
        self.current_operation_type = operation_type
        self.current_attack_ammo = ammo

    def confirm_attack_operation(self, operation_type, attack_ammo=None, target=None):
        """确认攻击操作"""
        if operation_type == OperationType.ATTACK:
            if target is None:
                # 如果还没有选择目标，显示提示
                print("请先在左侧选择攻击目标")
                return

        self.calculate(operation_type, attack_ammo, target)

    def calculate_player_positions(self):
        """计算玩家在圆圈上的位置"""
        positions = {}
        if not hasattr(self, 'left_widget'):
            return positions

        center_x = self.left_widget.width() // 2
        center_y = self.left_widget.height() // 2
        radius = min(center_x, center_y) - 50

        # 显示所有玩家，包括死亡的
        all_players = list(self.game.players)
        count = len(all_players)

        if count == 0:
            return positions

        for i, player in enumerate(all_players):
            angle = 2 * math.pi * i / count - math.pi / 2  # 从顶部开始
            x = center_x + int(radius * math.cos(angle))
            y = center_y + int(radius * math.sin(angle))
            positions[player] = (x, y)

        return positions

    def disable_all_operations(self):
        """禁用所有操作按钮"""
        self.load_btn.setEnabled(False)
        self.defence_btn.setEnabled(False)
        self.single_attack_btn.setEnabled(False)
        self.double_attack_btn.setEnabled(False)
        self.nuclear_attack_btn.setEnabled(False)


class ResultPage(QWidget):
    def __init__(self, main_window, winner):
        super().__init__()
        self.main_window = main_window
        self.winner = winner
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 结果显示 - 使用更大的字体和间距
        human_player = None
        if self.winner and hasattr(self.winner, 'name'):
            human_player = self.winner.name == "玩家"

        if human_player:
            result_text = "获胜！"
            color = "green"
        elif self.winner is False:
            result_text = "平局！"
            color = "blue"
        else:
            result_text = "惜败！"
            color = "red"

        result_label = QLabel(result_text)
        result_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        result_font = QFont()
        result_font.setPointSize(48)  # 更大的字体
        result_label.setFont(result_font)
        result_label.setStyleSheet(f"color: {color}; margin: 40px;")  # 添加边距
        layout.addWidget(result_label)

        layout.addStretch()

        # 返回按钮 - 更大的按钮
        back_btn = QPushButton("返回开始页面")
        back_btn.setFixedHeight(60)  # 更高的按钮
        back_btn_font = QFont()
        back_btn_font.setPointSize(16)  # 更大的字体
        back_btn.setFont(back_btn_font)
        back_btn.clicked.connect(self.main_window.show_start_page)
        layout.addWidget(back_btn)

        # 添加底部边距
        layout.addStretch()

        self.setLayout(layout)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("小兵小兵")
        self.setMinimumSize(600, 400)

        # 设置窗口图标
        try:
            self.setWindowIcon(QIcon("./icon.ico"))
        except:
            pass

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout(self.central_widget)

        self.show_start_page()

    def show_start_page(self):
        """显示开始页面"""
        self.clear_layout()
        self.start_page = StartPage(self)
        self.layout.addWidget(self.start_page)

    def start_offline_game(self):
        """开始离线游戏"""
        dialog = AISelectionDialog(self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            ai_count = dialog.ai_spinbox.value()
            self.show_offline_page(ai_count)

    def show_offline_page(self, ai_count):
        """显示离线页面"""
        self.clear_layout()
        self.offline_page = OfflinePage(self, ai_count)
        self.layout.addWidget(self.offline_page)

    def show_result_page(self, winner):
        """显示结果页面"""
        self.clear_layout()
        self.result_page = ResultPage(self, winner)
        self.layout.addWidget(self.result_page)

    def clear_layout(self):
        """清除布局中的所有widget"""
        for i in reversed(range(self.layout.count())):
            widget = self.layout.itemAt(i).widget()
            if widget:
                widget.setParent(None)


def main():
    app = QApplication(sys.argv)

    # 设置应用程序图标
    try:
        app.setWindowIcon(QIcon("./icon.ico"))
    except:
        pass

    window = MainWindow()
    window.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()
